package com.hzz.mall.seckill.scheduled;

import com.hzz.mall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 *秒杀商品的定时上架
 *
 */
@Service
@Slf4j
public class SeckillSkuSchedule {
    @Autowired
    SeckillService seckillService;
    @Autowired
    RedissonClient redissonClient;

    //秒杀商品上架功能的锁
    private final String upload_lock = "seckill:upload:lock";
    /**
     * 幂等性处理，商品上架之后不要重复上架
     */
    @Async
    @Scheduled(cron = "*/5 * * * * ?")
    public void uploadSeckillSkuLast3day(){
        log.info("上架秒杀的商品信息...");
        /**
         *  分布式锁，比如在分布式开发下，有三台机器，只要有一个机器上架秒杀商品就可以了，加锁
         *  只允许上架一次
         **/
        RLock lock = redissonClient.getLock(upload_lock);
        try {
            lock.lock(10, TimeUnit.SECONDS);//锁住
            seckillService.uploadSeckillSkuLast3day();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();// 解锁
        }

    }
}
